<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-teal-500 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <Layers class="w-8 h-8 text-white"/>
          </div>
          <CardTitle class="text-2xl text-slate-800">{{ t('multitaskTest.title') }}</CardTitle>
          <p class="text-slate-600 mt-2">{{ t('multitaskTest.description') }}</p>
        </CardHeader>

        <CardContent class="space-y-6">
          <div class="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100">
            <h3 class="font-semibold text-teal-900 mb-4 flex items-center gap-2">
              <Star class="w-5 h-5"/>
              测试说明
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                <p>{{ t('multitaskTest.instruction1') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                <p>{{ t('multitaskTest.instruction2') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                <p>{{ t('multitaskTest.instruction3') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                <p>{{ t('multitaskTest.instruction4') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-teal-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">5</span>
                <p>{{ t('multitaskTest.instruction5') }}</p>
              </div>
            </div>
          </div>

          <div class="bg-gradient-to-r from-orange-50 to-yellow-50 rounded-xl p-6 border border-orange-100">
            <h3 class="font-semibold text-orange-900 mb-4 flex items-center gap-2">
              <Star class="w-5 h-5"/>
              {{ t('multitaskTest.strategyTipsTitle') }}
            </h3>
            <div class="space-y-2 text-slate-700">
              <p>• <span class="font-semibold">{{ t('multitaskTest.strategy1') }}</span>：{{ t('multitaskTest.strategy1Desc') }}</p>
              <p>• <span class="font-semibold">{{ t('multitaskTest.strategy2') }}</span>：{{ t('multitaskTest.strategy2Desc') }}</p>
              <p>• <span class="font-semibold">{{ t('multitaskTest.strategy3') }}</span>：{{ t('multitaskTest.strategy3Desc') }}</p>
            </div>
          </div>

          <div class="grid md:grid-cols-3 gap-4">
            <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
              <div class="text-2xl font-bold text-teal-600 mb-1">3</div>
              <div class="text-sm text-teal-700">{{ t('multitaskTest.timeLimitLabel') }}</div>
            </div>
            <div class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
              <div class="text-2xl font-bold text-cyan-600 mb-1">4</div>
              <div class="text-sm text-cyan-700">{{ t('multitaskTest.taskTypesLabel') }}</div>
            </div>
            <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
              <div class="text-2xl font-bold text-slate-600 mb-1">∞</div>
              <div class="text-sm text-slate-700">{{ t('multitaskTest.taskCountLabel') }}</div>
            </div>
          </div>

          <Button
            class="w-full bg-gradient-to-r from-teal-500 to-cyan-500 hover:from-teal-600 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleStartTest"
          >
            {{ t('multitaskTest.startTest') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div v-else-if="stage === 'test'" class="max-w-6xl mx-auto space-y-6">
    <transition appear name="fade">
      <div>
        <!-- Top Status Bar -->
        <div
          class="flex flex-col sm:flex-row gap-4 items-center justify-between bg-white/80 backdrop-blur-sm rounded-lg p-4 border border-teal-200">
          <div class="flex items-center gap-6">
            <Badge class="bg-teal-100 text-teal-700 border-teal-300" variant="outline">
              {{ t('multitaskTest.completed') }}: {{ completedTasks }}
            </Badge>
            <div class="flex items-center gap-2 text-slate-600">
              <Trophy class="w-4 h-4"/>
              <span class="font-semibold">{{ totalScore }} {{ t('multitaskTest.points') }}</span>
            </div>
            <Badge class="bg-slate-100 text-slate-700 border-slate-300" variant="outline">
              {{ t('multitaskTest.switches') }}: {{ taskSwitches }}{{ t('multitaskTest.times') }}
            </Badge>
          </div>

          <div class="flex items-center gap-2">
            <Clock class="w-4 h-4 text-slate-500"/>
            <span :class="['font-mono', 'text-lg', 'font-bold', timeLeft <= 30 ? 'text-red-500' : 'text-slate-700']">
              {{ Math.floor(timeLeft / 60) }}:{{ (timeLeft % 60).toString().padStart(2, '0') }}
            </span>
          </div>
        </div>

        <!-- Tasks Grid -->
        <div class="grid md:grid-cols-3 gap-6">
          <transition-group name="list">
            <div v-for="(task, index) in currentTasks" :key="task.id">
              <Card
                :class="[
                  'cursor-pointer', 'transition-all', 'duration-300',
                  { 'bg-gradient-to-br from-teal-50 to-cyan-50 border-teal-300 shadow-lg scale-105': task.id === activeTaskId },
                  { 'bg-white/80 border-slate-200 hover:border-teal-200': task.id !== activeTaskId },
                  { 'opacity-50': task.completed }
                ]"
                @click="handleTaskSwitch(task.id)"
              >
                <CardHeader class="pb-3">
                  <CardTitle class="text-sm font-semibold flex items-center justify-between">
                    <span>{{ taskTypeNames[task.type] }}</span>
                    <Badge :class="[
                      'text-xs',
                      task.id === activeTaskId
                        ? 'bg-teal-100 text-teal-700 border-teal-300'
                        : 'bg-slate-100 text-slate-600 border-slate-200'
                    ]" variant="outline">
                      {{ task.id === activeTaskId ? t('multitaskTest.active') : t('multitaskTest.waiting') }}
                    </Badge>
                  </CardTitle>
                </CardHeader>

                <CardContent class="pt-0">
                  <transition mode="out-in" name="fade">
                    <div v-if="task.completed" class="text-center py-8 text-green-600">
                      <Trophy class="w-8 h-8 mx-auto mb-2"/>
                      <p class="font-semibold">{{ t('multitaskTest.taskCompleted') }}</p>
                      <p class="text-xs">{{ t('multitaskTest.pointsEarned', { score: task.score }) }}</p>
                    </div>
                    <div v-else>
                      <!-- Math Task -->
                      <div v-if="task.type === 'math'" class="space-y-4">
                        <h3 class="text-lg font-semibold text-center text-slate-700">{{ task.content.question }}</h3>
                        <div class="grid grid-cols-2 gap-2">
                          <Button
                            v-for="num in task.content.options"
                            :key="num"
                            class="plain-Button"
                            @click.stop="handleMathAnswer(task.id, num)"
                          >
                            {{ num }}
                          </Button>
                        </div>
                      </div>

                      <!-- Memory Task -->
                      <div v-else-if="task.type === 'memory'">
                        <div v-if="task.content.showSequence" class="text-center space-y-4">
                          <h3 class="font-semibold text-slate-700">{{ t('multitaskTest.rememberSequence') }}</h3>
                          <div class="text-2xl font-mono tracking-wider text-teal-600 font-bold">
                            {{ task.content.sequence.join(' - ') }}
                          </div>
                          <div class="text-sm text-slate-500">
                            ({{ task.content.sequence.length }}{{ t('multitaskTest.digits') }}
                          </div>
                        </div>
                        <div v-else class="space-y-4">
                          <h3 class="font-semibold text-center text-slate-700">{{ t('multitaskTest.clickInOrder') }}</h3>
                          <div class="text-center text-sm text-slate-600">
                            {{ t('multitaskTest.progress') }}: {{ task.content.userSequence.length }}/{{ task.content.sequence.length }}
                          </div>
                          <div class="text-center text-xs text-teal-600 font-mono">
                            {{ t('multitaskTest.entered') }}: {{ task.content.userSequence.join(' - ') || t('multitaskTest.empty') }}
                          </div>
                          <div class="grid grid-cols-3 gap-2">
                            <Button
                              v-for="num in [1,2,3,4,5,6,7,8,9]"
                              :key="num"
                              class="plain-Button"
                              @click.stop="handleMemoryAnswer(task.id, num)"
                            >
                              {{ num }}
                            </Button>
                          </div>
                        </div>
                      </div>

                      <!-- Reaction Task -->
                      <div v-else-if="task.type === 'reaction'" class="space-y-4">
                        <h3 class="font-semibold text-center text-slate-700">
                          {{ t('multitaskTest.click') }}<span class="text-lg font-bold text-teal-600">{{
                            colorMap[task.content.targetColor]?.name
                          }}</span>
                        </h3>
                        <div class="grid grid-cols-3 gap-2">
                          <Button
                            v-for="(colorData, colorKey) in colorMap"
                            :key="colorKey"
                            :class="['w-full h-12 rounded-lg shadow-sm border border-white/20 transition-all duration-200', colorData.bg]"
                            :title="colorData.name"
                            @click.stop="handleReactionAnswer(task.id, colorKey)"
                          />
                        </div>
                      </div>

                      <!-- Sequence Task -->
                      <div v-else-if="task.type === 'sequence'" class="space-y-4">
                        <h3 class="font-semibold text-center">{{ t('multitaskTest.findNextItem') }}</h3>
                        <div class="text-center text-lg">
                          {{ task.content.pattern.join(' → ') }} → ?
                        </div>
                        <div class="grid grid-cols-2 gap-2">
                          <Button
                            v-for="(option, index) in task.content.options"
                            :key="index"
                            class="plain-Button"
                            @click.stop="handleSequenceAnswer(task.id, option)"
                          >
                            {{ option }}
                          </Button>
                        </div>
                      </div>
                    </div>
                  </transition>
                </CardContent>
              </Card>
            </div>
          </transition-group>
        </div>
      </div>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-teal-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-teal-500 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
            <Trophy class="w-10 h-10 text-white"/>
          </div>

          <h2 class="card-title text-3xl text-slate-800 mb-2">{{ t('multitaskTest.testComplete') }}</h2>
          <div class="text-6xl font-bold bg-gradient-to-r from-teal-500 to-cyan-500 bg-clip-text text-transparent">
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">{{ t('multitaskTest.multitaskingScore') }}</p>
        </CardHeader>

        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div class="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
              <div class="text-2xl font-bold text-teal-600 mb-1">{{ completedTasks }}</div>
              <div class="text-sm text-teal-700">{{ t('multitaskTest.completedTasks') }}</div>
            </div>
            <div class="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
              <div class="text-2xl font-bold text-cyan-600 mb-1">{{ totalScore }}</div>
              <div class="text-sm text-cyan-700">{{ t('multitaskTest.totalScore') }}</div>
            </div>
          </div>

          <div class="space-y-3">
            <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
              <span class="text-slate-600">{{ t('multitaskTest.taskEfficiency') }}</span>
              <span class="font-semibold text-slate-800">{{ results.efficiency }}{{ t('multitaskTest.pointsPerTask') }}</span>
            </div>
            <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
              <span class="text-slate-600">{{ t('multitaskTest.multitaskingEfficiency') }}</span>
              <span class="font-semibold text-slate-800">{{ results.multitaskingEfficiency }}{{ t('multitaskTest.tasksPerMinute') }}</span>
            </div>
            <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
              <span class="text-slate-600">{{ t('multitaskTest.numberOfSwitches') }}</span>
              <span class="font-semibold text-slate-800">{{ taskSwitches }}{{ t('multitaskTest.times') }}</span>
            </div>
            <div class="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
              <span class="text-slate-600">{{ t('multitaskTest.switchingEfficiency') }}</span>
              <span class="font-semibold text-slate-800">{{ results.switchingEfficiency }}{{ t('multitaskTest.switchesPerTask') }}</span>
            </div>
          </div>

          <div class="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-lg p-4 border border-teal-200">
            <h4 class="font-semibold text-teal-800 mb-2">{{ t('multitaskTest.scoreComposition') }}</h4>
            <div class="space-y-1 text-sm">
              <div class="flex justify-between">
                <span class="text-slate-600">{{ t('multitaskTest.baseScore') }}</span>
                <span class="text-slate-800">{{ Math.round(results.baseScore) }}{{ t('multitaskTest.points') }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-slate-600">{{ t('multitaskTest.completionBonus') }}</span>
                <span class="text-green-600">+{{ Math.round(results.completionBonus) }}{{ t('multitaskTest.points') }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-slate-600">{{ t('multitaskTest.timeBonus') }}</span>
                <span class="text-blue-600">+{{ Math.round(results.timeBonus) }}{{ t('multitaskTest.points') }}</span>
              </div>
              <div class="flex justify-between">
                <span class="text-slate-600">{{ t('multitaskTest.switchingStrategy') }}</span>
                <span :class="results.switchingScore >= 0 ? 'text-green-600' : 'text-red-600'">
                  {{ results.switchingScore >= 0 ? '+' : '' }}{{ Math.round(results.switchingScore) }}{{ t('multitaskTest.points') }}
                </span>
              </div>
            </div>
          </div>

          <Button
            class="w-full bg-gradient-to-r from-teal-500 to-cyan-500 hover:from-teal-600 hover:to-cyan-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleComplete"
          >
            {{ t('multitaskTest.viewDetailedResults') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, watch, computed} from 'vue';
import {Layers, Clock, Trophy, Star} from 'lucide-vue-next';
import { useGlobalI18n } from '~/composables/useGlobalI18n';

const { t } = useGlobalI18n();

const emit = defineEmits(['complete']);

// --- State ---
const stage = ref('instructions'); // 'instructions', 'test', 'results'
const currentTasks = ref([]);
const activeTaskId = ref(null);
const timeLeft = ref(180); // 3 minutes
const startTime = ref(0);
const totalScore = ref(0);
const completedTasks = ref(0);
const taskSwitches = ref(0);

let mainTimer = null;
const memoryTimers = new Map();

// --- Constants ---
const taskTypeNames = {
  math: t('multitaskTest.taskTypeMath'),
  memory: t('multitaskTest.taskTypeMemory'),
  reaction: t('multitaskTest.taskTypeReaction'),
  sequence: t('multitaskTest.taskTypeSequence')
};

const colorMap = {
  red: {bg: 'bg-red-500', name: t('multitaskTest.colorRed')},
  blue: {bg: 'bg-blue-500', name: t('multitaskTest.colorBlue')},
  green: {bg: 'bg-green-500', name: t('multitaskTest.colorGreen')},
  yellow: {bg: 'bg-yellow-500', name: t('multitaskTest.colorYellow')},
  purple: {bg: 'bg-purple-500', name: t('multitaskTest.colorPurple')},
  orange: {bg: 'bg-orange-500', name: t('multitaskTest.colorOrange')}
};

// --- Task Generation ---
const generateMathTask = () => {
  const operations = ['+', '-', '*'];
  const operation = operations[Math.floor(Math.random() * operations.length)];
  let a, b, answer, question;

  switch (operation) {
    case '+':
      a = Math.floor(Math.random() * 15) + 1;
      b = Math.floor(Math.random() * 15) + 1;
      answer = a + b;
      question = `${a} + ${b} = ?`;
      break;
    case '-':
      a = Math.floor(Math.random() * 20) + 10;
      b = Math.floor(Math.random() * (a - 1)) + 1;
      answer = a - b;
      question = `${a} - ${b} = ?`;
      break;
    case '*':
      a = Math.floor(Math.random() * 8) + 2;
      b = Math.floor(Math.random() * 8) + 2;
      answer = a * b;
      question = `${a} × ${b} = ?`;
      break;
  }

  const options = new Set([answer]);
  while (options.size < 6) {
    const distractor = answer + Math.floor(Math.random() * 10) - 5;
    if (distractor >= 0 && distractor !== answer) {
      options.add(distractor);
    }
  }

  return {question, answer, options: Array.from(options).sort((a, b) => a - b)};
};

const generateMemoryTask = () => {
  const length = Math.floor(Math.random() * 3) + 4; // 4-6 digits
  const sequence = Array.from({length}, () => Math.floor(Math.random() * 9) + 1);
  return {sequence, userSequence: [], showSequence: true};
};

const generateReactionTask = () => {
  const colors = Object.keys(colorMap);
  const targetColor = colors[Math.floor(Math.random() * colors.length)];
  return {targetColor};
};

const generateSequenceTask = () => {
  const patterns = [
    {pattern: ['A', 'B', 'C'], next: 'D'},
    {pattern: ['1', '2', '3'], next: '4'},
    {pattern: ['○', '●', '○'], next: '●'},
    {pattern: ['△', '□', '△'], next: '□'}
  ];

  const selected = patterns[Math.floor(Math.random() * patterns.length)];
  const options = new Set([selected.next]);
  const allOptions = ['A', 'B', 'C', 'D', 'E', '1', '2', '3', '4', '5', '○', '●', '△', '□'];
  while (options.size < 4) {
    const option = allOptions[Math.floor(Math.random() * allOptions.length)];
    if (!options.has(option)) {
      options.add(option);
    }
  }

  return {
    pattern: selected.pattern,
    nextItem: selected.next,
    options: Array.from(options).sort(() => Math.random() - 0.5)
  };
};

const createNewTask = () => {
  const types = ['math', 'memory', 'reaction', 'sequence'];
  const type = types[Math.floor(Math.random() * types.length)];
  const id = `${type}_${Date.now()}_${Math.random()}`;

  let content;
  switch (type) {
    case 'math':
      content = generateMathTask();
      break;
    case 'memory':
      content = generateMemoryTask();
      break;
    case 'reaction':
      content = generateReactionTask();
      break;
    case 'sequence':
      content = generateSequenceTask();
      break;
  }

  return {id, type, content, completed: false, score: 0};
};

// --- Test Flow ---
const handleStartTest = () => {
  stage.value = 'test';
  startTime.value = Date.now();
  currentTasks.value = [createNewTask(), createNewTask(), createNewTask()];
  activeTaskId.value = currentTasks.value[0].id;

  mainTimer = setInterval(() => {
    if (timeLeft.value <= 1) {
      stage.value = 'results';
      clearInterval(mainTimer);
    } else {
      timeLeft.value--;
    }
  }, 1000);
};

const handleTaskSwitch = (taskId) => {
  if (taskId !== activeTaskId.value) {
    activeTaskId.value = taskId;
    taskSwitches.value++;
  }
};

const handleTaskComplete = (taskId, score) => {
  const taskIndex = currentTasks.value.findIndex(t => t.id === taskId);
  if (taskIndex === -1) return;

  // Clear any running memory timers for this task
  if (memoryTimers.has(taskId)) {
    clearTimeout(memoryTimers.get(taskId));
    memoryTimers.delete(taskId);
  }

  currentTasks.value[taskIndex] = {...currentTasks.value[taskIndex], completed: true, score};
  totalScore.value += score;
  completedTasks.value++;

  setTimeout(() => {
    const newTask = createNewTask();
    currentTasks.value[taskIndex] = newTask;
    if (activeTaskId.value === taskId) {
      activeTaskId.value = newTask.id;
    }
  }, 800);
};

// --- Answer Handlers ---
const handleMathAnswer = (taskId, answer) => {
  const task = currentTasks.value.find(t => t.id === taskId);
  if (!task) return;
  const score = answer === task.content.answer ? 10 : 0;
  handleTaskComplete(taskId, score);
};

const handleMemoryAnswer = (taskId, num) => {
  const taskIndex = currentTasks.value.findIndex(t => t.id === taskId);
  if (taskIndex === -1) return;

  const task = currentTasks.value[taskIndex];
  const newUserSequence = [...task.content.userSequence, num];
  const currentIndex = newUserSequence.length - 1;

  if (newUserSequence[currentIndex] !== task.content.sequence[currentIndex]) {
    handleTaskComplete(taskId, 0); // Wrong number
    return;
  }

  if (newUserSequence.length === task.content.sequence.length) {
    handleTaskComplete(taskId, 15); // Correct sequence
  } else {
    // Update sequence in place
    currentTasks.value[taskIndex].content.userSequence = newUserSequence;
  }
};

const handleReactionAnswer = (taskId, clickedColor) => {
  const task = currentTasks.value.find(t => t.id === taskId);
  if (!task) return;
  const score = clickedColor === task.content.targetColor ? 8 : 0;
  handleTaskComplete(taskId, score);
};

const handleSequenceAnswer = (taskId, answer) => {
  const task = currentTasks.value.find(t => t.id === taskId);
  if (!task) return;
  const score = answer === task.content.nextItem ? 12 : 0;
  handleTaskComplete(taskId, score);
};

// --- Final Results ---
const results = computed(() => {
  if (stage.value !== 'results') return {};

  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);
  const efficiency = completedTasks.value > 0 ? Math.round((totalScore.value / completedTasks.value)) : 0;

  const baseScore = Math.min(100, (totalScore.value / 5));
  const completionBonus = Math.min(20, completedTasks.value * 2);
  const timeBonus = Math.max(0, (180 - timeUsed) / 18);

  const switchingEfficiency = completedTasks.value > 0 ? taskSwitches.value / completedTasks.value : 0;
  let switchingScore = 0;

  if (switchingEfficiency <= 1.5) {
    switchingScore = Math.min(15, 15 - (switchingEfficiency - 0.5) * 10);
  } else if (switchingEfficiency <= 3) {
    switchingScore = Math.max(-10, 5 - (switchingEfficiency - 1.5) * 10);
  } else {
    switchingScore = Math.max(-25, -10 - (switchingEfficiency - 3) * 5);
  }

  const finalScore = Math.round(Math.max(0, Math.min(100, baseScore + completionBonus + timeBonus + switchingScore)));
  const multitaskingEfficiency = completedTasks.value > 0 ? Math.round((completedTasks.value * 60) / (timeUsed / 60)) : 0;

  return {
    finalScore,
    efficiency,
    multitaskingEfficiency,
    switchingEfficiency: Math.round(switchingEfficiency * 100) / 100,
    baseScore,
    completionBonus,
    timeBonus,
    switchingScore
  };
});

const handleComplete = () => {
  emit('complete', {
    id: Date.now().toString(),
    testType: 'multitask',
    score: results.value.finalScore,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: {
      completedTasks: completedTasks.value,
      totalScore: totalScore.value,
      taskSwitches: taskSwitches.value,
      efficiency: results.value.efficiency,
      averageScorePerTask: completedTasks.value > 0 ? Math.round(totalScore.value / completedTasks.value) : 0,
      baseScore: Math.round(results.value.baseScore),
      completionBonus: Math.round(results.value.completionBonus),
      timeBonus: Math.round(results.value.timeBonus),
      switchingEfficiency: results.value.switchingEfficiency,
      switchingScore: Math.round(results.value.switchingScore),
      multitaskingEfficiency: results.value.multitaskingEfficiency
    }
  });
};

// --- Lifecycle & Watchers ---
onMounted(() => {
  onUnmounted(() => {
    if (mainTimer) clearInterval(mainTimer);
    memoryTimers.forEach(timer => clearTimeout(timer));
    memoryTimers.clear();
  });
});

watch(currentTasks, (newTasks, oldTasks) => {
  newTasks.forEach(task => {
    if (task.type === 'memory' && task.content.showSequence && !memoryTimers.has(task.id)) {
      const timer = setTimeout(() => {
        const taskIndex = currentTasks.value.findIndex(t => t.id === task.id);
        if (taskIndex !== -1) {
          currentTasks.value[taskIndex].content.showSequence = false;
        }
        memoryTimers.delete(task.id);
      }, Math.max(2000, task.content.sequence.length * 600));
      memoryTimers.set(task.id, timer);
    }
  });
}, {deep: true});

</script>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.list-enter-active, .list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}


</style>